package com.fuyu.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyu.common.exception.CRUDException;
import com.fuyu.common.utils.PageHelperUtil;
import com.fuyu.system.dao.SysUserDao;
import com.fuyu.system.entity.SysUser;
import com.fuyu.system.models.search.SysUserSearch;
import com.fuyu.system.models.vo.user.SysUserBaseInfoVO;
import com.fuyu.system.models.vo.user.SysUserListVO;
import com.fuyu.system.service.BaseCrud;
import com.fuyu.system.service.SysUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户信息表(SysUser)表服务实现类
 *
 * @author makejava
 * @since 2024-04-01 23:29:32
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService, BaseCrud<SysUser> {


    @Override
    public SysUserBaseInfoVO getUserBaseInfo(String userId) {
        SysUser sysUser = this.getOne(
                getLambdaQueryWrapper().eq(SysUser::getUserId, userId)
        );
        if (sysUser == null) {
            throw new CRUDException("用户不存在");
        }
        return SysUserBaseInfoVO.toVO(sysUser);
    }

    @Override
    public Boolean addUser(SysUser entity) {
        SysUser sysUser = this.getOne(getLambdaQueryWrapper().eq(SysUser::getUsername, entity.getUsername()));

        if (sysUser != null) {
            throw new CRUDException("当前用户名已存在");
        }

        return this.save(entity);
    }

    @Override
    public Boolean editUser(SysUser entity) {
        return this.update(entity, getLambdaQueryWrapper().eq(SysUser::getUserId, entity.getUserId()));
    }

    @Override
    public PageInfo<SysUserListVO> getList(SysUserSearch params) {

        PageHelper.startPage(params.getPage(), params.getSize());
        List<SysUser> list = this.list();
        List<SysUserListVO> sysUserList = list.stream().map(SysUserListVO::toEntity).toList();

        return PageHelperUtil.format(list, sysUserList);
    }
}

